var apiHost = wx.getStorageSync("apiHost"); //请求地址
var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

var AppidFlag = wx.getStorageSync('AppidFlag');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,          //tabNum
    tabConheight:0,         //tab高度
    showFormatCon:false,    //展示规格
    showCoupon:false,       //展示红包
    propertys :'',          //商品规格
    sku : '',               //商品sku
    goodsNum: 1,            //商品数量
    goodsFeedbacks : '',    //商品评价
    feedbacksOrder : '',    //评价筛选
    feedbacksNum : 1  ,     //评论数量
    feedbacksList : '',     //评论集合
    proName0:'',            //sku属性值默认
    proName1: '',           //sku属性值默认
    cartCount : 0,          //购物车数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var spuid = options.spuid;
    var token = wx.getStorageSync('token');       //用户的token信息

    // spuid = '3697a9b25d2c4f5c985acb2060f50666';

    that.setData({
      token: token,
      spuid: spuid
    })
    
    that.getGoodsDetail(spuid);                 //获取商品详情
    that.getCouponDetail(token, spuid);         //获取红包信息
    that.getCartCount(token);                   //获取购物车数量
    that.getGoodsSku('', spuid);                //商品sku
    that.getGoodsFeedbacks(spuid, '', '',0,10);  //商品评价

    that.tabConheight();
  },

  /**
   * 获取商品详情
   */
  getGoodsDetail: function (goodsId) {
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/yh2/detail2", //仅为示例，并非真实的接口地址
      data: {
        id: goodsId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        console.log(res)

        if (code == "10000") {
          that.setData({
            goodsDetail: res.data.data
          })
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 获取红包信息
   */
  getCouponDetail: function (token, goodsId){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/coupon/info", //仅为示例，并非真实的接口地址
      data: {
        appId: AppidFlag,
        token: token,
        'type' : '1',
        goodsId: goodsId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          that.setData({
            CouponDetail: res.data.data
          })
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },


  /**
   * 领取优惠券
   */
  receiveCoupon:function(e){
    var that = this;
    var couponid = e.currentTarget.dataset.couponid;
    var token = that.data.token;
    var spuid = that.data.spuid;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/coupon/receive", //仅为示例，并非真实的接口地址
      data: {
        appId: AppidFlag,
        token: token,
        couponId: couponid,
        'type': '1'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          // that.showMsg('领取成功');
          wx.showToast({
            title: '领取成功',
            icon: 'succes',
            duration: 1000,
            mask: true
          })
          that.getCouponDetail(token, spuid);         //获取红包信息
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 商品sku
   */
  getGoodsSku: function (queryParam,spuId){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/yh2/getSkuPropertys2", //仅为示例，并非真实的接口地址
      data: {
        queryParam: queryParam,
        spuId: spuId,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var data = res.data.data;
          var propertys = data.propertys;
          var sku = data.sku;
          
          that.setProName(propertys); //设置pro属性，（点击传值用）

          that.setData({
            propertys: propertys,
            sku : sku
          })
         
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 设置pro属性，（点击传值用）
   */
  setProName: function (propertys){
    var that = this;
    for (var i = 0; propertys.length > i; i++) {
      var proItem = propertys[i].items;

      for (var j = 0; proItem.length > j; j++) {
        var isChose = proItem[j].isChose;

        if ("chosed" == isChose) {
          if (i == 0) {
            var proName0 = proItem[j].name;
            that.setData({
              proName0: proName0
            })
          } else {
            var proName1 = proItem[j].name;
            that.setData({
              proName1: proName1
            })
          }
        }
      }
    }
  },

  /**
   * 商品sku点击事件
   */
  porClick:function(e){
    var that=this;
    var proname = e.currentTarget.dataset.proname;
    var pindex = e.currentTarget.dataset.pindex;

    var spuid = that.data.spuid;

    var proName0 = that.data.proName0;
    var proName1 = that.data.proName1;

    if (pindex==0){
      proName0 = proname
    }
    if (pindex == 1) {
      proName1 = "_" +proname
    }
    var queryParam = proName0 + proName1
    that.getGoodsSku(queryParam,spuid);
  },

  /**
   * 获取购物车数量
   */
  getCartCount: function (token){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/shoppingcartCount", //仅为示例，并非真实的接口地址
      data: {
        appId: AppidFlag,
        token: token
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            cartCount: res.data.data
          })
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 详情页加入购物车
   */
  addShopCartIndex:function(e){
    var that = this;
    var mainskuid = e.currentTarget.dataset.mainskuid;
    var token = that.data.token;
    that.addShopCart(mainskuid, 1, token);
  },
  /**
   * 规格详情添加购物车
   */
  addShopCartPro: function (e) {
    var that = this;
    var skuid = e.currentTarget.dataset.skuid;
    var token = that.data.token;
    var goodsNum = that.data.goodsNum;
    
    that.addShopCart(skuid, goodsNum, token);
  },

  /**
   * 加入购物车方法（通用）
   */
  addShopCart: function (skuId, count, token){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/addshoppingcart", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        skuId: skuId,
        count: count
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        console.log(res)
        if (code == "10000") {
          that.getCartCount(token);
          wx.showToast({
            title: '加入成功',
            icon: 'succes',
            duration: 1000,
            mask: true
          })
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 数量减少
   */
  goodsNumSub :function(){
    var that = this;
    var goodsNum = that.data.goodsNum;

    if (goodsNum>1){
      that.setData({
        goodsNum: goodsNum-1
      });
    }
  },
  /**
   * 数量增加
   */
  goodsNumAdd:function(){
    var that = this;
    var goodsNum = that.data.goodsNum;

    that.setData({
      goodsNum: goodsNum + 1
    });
  },

  /**
   * 商品评价
   */
  getGoodsFeedbacks: function (spuId, typeFlag, like, start,length){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/yh2/getSpuFeedbacks2", //仅为示例，并非真实的接口地址
      data: {
        id: spuId,
        'type': typeFlag,
        like: like,
        start: start,
        length: length
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var feedbacksData = res.data.data;
          that.feedbacksPaging(start, feedbacksData);
        } else {
          that.showMsg(msg);
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 商品分页
   */
  feedbacksPaging: function (start, feedbacksData) {
    var that = this;
    
    if (start > 0) {
      var feedbacksLists = that.data.feedbacksList;
      var feedbacks = feedbacksData.list
      // 追加数据
      for (var i = 0; i < feedbacks.length; i++) {
        feedbacksLists.push(feedbacks[i])
      }
      start = parseInt(start) + 1;
    } else {
      var feedbacksLists = feedbacksData.list;
      start = 1;
    }

    that.setData({
      goodsFeedbacks: feedbacksData,
      feedbacksList: feedbacksLists,
      startFlag: start
    })
  },

  /**
   * 点击 评论筛选
   */
  clickfbOrder:function(e){
    var that = this;
    var orderflag = e.currentTarget.dataset.orderflag;
   
    var spuid = that.data.spuid;

    that.checkImgLike(spuid,orderflag,0);
  },

  /**
   * 判断排序方式
   */
  checkImgLike: function (spuid, orderflag, start){
    var that = this;
    var typeFlag = '';
    var like = '';
    if (orderflag == 'image') {
      typeFlag = 'image';
    }
    if (orderflag == 'like') {
      like = 5;
    }

    that.setData({
      feedbacksOrder: orderflag
    })

    that.getGoodsFeedbacks(spuid, typeFlag, like, start, 10);  //商品评价
  },

  /**
   * 下拉评论
   */
  goodsFeedbacksBot : function(){
    var that = this;
    var spuid = that.data.spuid;
    var orderflag = that.data.feedbacksOrder;
    var startFlag = that.data.startFlag;
    that.checkImgLike(spuid, orderflag, startFlag);
  },

  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTba: e.detail.current
    });
  },
  //点击切换
  clickTab: function (e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  /**
   * 计算tab高度
   */
  tabConheight: function () {
    var that = this;
    var query = wx.createSelectorQuery();

    var tablistEnjoyConHeight = "";
    var bottomBtnConHeight = "";

    query.select('#tablistEnjoyCon').boundingClientRect()
    query.select('#bottomBtnCon').boundingClientRect()
    query.exec(function (res) {
      tablistEnjoyConHeight = res[0].height;
      bottomBtnConHeight = res[1].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            tabConheight: res.windowHeight - tablistEnjoyConHeight - bottomBtnConHeight
          });
        }
      });
    });
  },

  /**
   * 开启选择规格
   */
  showFormat:function(){
    var that = this;
    that.setData({
      showFormatCon: true
    })
  },
  showCoupon: function () {
    var that = this;
    that.setData({
      showCoupon: true
    })
  },

  /**
   * 关闭选择规格
   */
  closeFormatCon:function(){
    var that = this;
    that.setData({
      showFormatCon: false
    })
  },
  closeCoupon:function(){
    var that = this;
    that.setData({
      showCoupon: false
    })
  },

  /**
   * 跳转订单详情
   */
  goFillOrder:function(e){
    var that = this;
    var skuidcounts = e.currentTarget.dataset.skuidcounts;
    wx.navigateTo({
      url: "../../order/fillOrder/fillOrder?skuidcounts=" + skuidcounts,
    })
  },

  /**
   * 跳转到购物车
   */
  goShopCart :function(){
    var that = this;
    wx.switchTab({
      url: "../../shopCart/shopCart"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  /**
   * 提示信息
   */
  showMsg: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    });
  },
})